import 'package:flutter/material.dart';

import '../../config/public_color.dart';
import '../../foundation/style/normal_text_style.dart';
import '../../model/key_value_model.dart';
import '../../tool/public_tool.dart';
import '../bar/public_search_bar.dart';
import '../divider/padding_divider.dart';
import '../indicator/empty_indicator.dart';
import '../item/check_box_item.dart';
import 'model/search_result_model.dart';

/// FileName search_view
///
/// @Author lax
/// @Date 2023/6/6
///
/// @Description

typedef SearchViewItemCallback = Function(KeyValueModel model, int index);

typedef SearchViewButtonCallback = Future<SearchResultModel?> Function(
    String? selectedId);

class SearchView extends StatefulWidget {
  final String? hintText;

  /// 已选中的用户id 多个用,拼接
  final String? selectedId;

  final String? title;

  final List<KeyValueModel> dataSource;

  /// 是否支持多选 默认false
  final bool multiSelect;

  /// 是否显示搜索框
  final bool showSearchBar;

  /// 搜索框右侧按钮
  final String? searchButtonText;
  final bool searchButtonEnable;

  final SearchViewItemCallback? onSelectedItem;

  final SearchViewButtonCallback? onPressedSearchButton;

  const SearchView({
    super.key,
    this.hintText,
    this.selectedId,
    this.title,
    this.dataSource = const [],
    this.multiSelect = false,
    this.showSearchBar = false,
    this.searchButtonText,
    this.searchButtonEnable = true,
    this.onSelectedItem,
    this.onPressedSearchButton,
  });

  @override
  State<StatefulWidget> createState() {
    return SearchViewState();
  }
}

class SearchViewState extends State<SearchView> {
  /// 搜索内容
  String filterText = '';

  /// 搜索框右侧按钮
  String? currentButtonSelectedId;
  String? currentButtonSelectedName;

  KeyValueModel? lastSelectModel;

  bool get isFilter {
    return filterText.isNotEmpty;
  }

  List<KeyValueModel> dataSource = [];

  List<KeyValueModel> filterDataSource = [];

  void selectModel(KeyValueModel userModel) {
    // 单选/多选处理
    if (lastSelectModel != userModel &&
        lastSelectModel != null &&
        !widget.multiSelect) {
      lastSelectModel?.select = false;
    }
    lastSelectModel = userModel;
    userModel.select = userModel.select == true ? false : true;
  }

  SearchResultModel getSelectData() {
    // 处理选中的数据
    List<KeyValueModel> checkList = [];
    for (var element in dataSource) {
      if (element.select == true) {
        checkList.add(element);
      }
    }
    final value = SearchResultModel(selectedList: checkList);
    return value;
  }

  /// 初始化选中的数据
  void initData() {
    for (var element in dataSource) {
      if (widget.selectedId != null && widget.selectedId != '') {
        var selectedList = widget.selectedId!.split(',');
        // 单选只获取第一个值
        if (!widget.multiSelect && selectedList.length > 1) {
          selectedList = [selectedList.first];
        }
        if (element.id == null && element.key == null) {
          element.select = selectedList.contains(element.value);
        } else {
          element.select = selectedList.contains(element.key) ||
              selectedList.contains(element.id.toString());
        }
        if (element.select == true) {
          lastSelectModel = element;
        }
      }
    }
  }

  /// 筛选搜索数据
  Future<void> searchFilterData() async {
    // 没有内容清空数据 不搜索
    filterDataSource = [];
    if (!isFilter) {
      return;
    }
    for (var element in dataSource) {
      if (element.value?.toUpperCase().contains(filterText.toUpperCase()) == true) {
        filterDataSource.add(element);
      }
    }
  }

  @override
  void initState() {
    super.initState();
    dataSource = widget.dataSource;
    initData();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Visibility(
          visible: widget.showSearchBar == true,
          child: PublicSearchBar(
            text: filterText,
            hintText: widget.hintText,
            buttonWidget: searchButton(),
            showButton: widget.searchButtonText != null,
            onChanged: (text) {
              filterText = text;
              setState(() {
                searchFilterData();
              });
            },
          ),
        ),
        Expanded(
          child: Visibility(
            visible: listIsNotEmpty(dataSource),
            replacement: EmptyIndicator(),
            child: widget.showSearchBar
                ? Scrollbar(child: listView())
                : listView(),
          ),
        ),
      ],
    );
  }

  Widget? searchButton() {
    if (widget.searchButtonText == null) {
      return null;
    }
    return GestureDetector(
      onTap: () async {
        if (widget.searchButtonEnable != true) {
          return;
        }
        final value =
            await widget.onPressedSearchButton!(currentButtonSelectedId);
        setState(() {
          currentButtonSelectedId = value?.buttonModel?.key;
          currentButtonSelectedName = value?.buttonModel?.value;
          dataSource = value?.selectedList ?? [];
          searchFilterData();
        });
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            (currentButtonSelectedId == null
                    ? widget.searchButtonText
                    : currentButtonSelectedName) ??
                '',
            textAlign: TextAlign.center,
            style: NormalTextStyle(color: PublicColor.darkText),
          ),
          Visibility(
            visible: widget.searchButtonEnable == true,
            child: Icon(
              Icons.keyboard_arrow_down,
              color: PublicColor.grayText,
              size: 16,
            ),
          ),
        ],
      ),
    );
  }

  Widget listView() {
    return ListView.separated(
      physics: const AlwaysScrollableScrollPhysics(),
      padding: EdgeInsets.zero,
      itemCount: isFilter ? filterDataSource.length : dataSource.length,
      itemBuilder: (BuildContext context, int index) {
        final model = isFilter ? filterDataSource[index] : dataSource[index];
        return CheckBoxItem(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          title: model.value ?? '',
          value: model.select,
          checkboxPosition: CheckboxPosition.left,
          onTap: () {
            setState(() {
              selectModel(model);
              if (model.select == true &&
                  !isFilter &&
                  widget.onSelectedItem != null) {
                widget.onSelectedItem!(model, index);
              }
            });
          },
        );
      },
      separatorBuilder: (BuildContext context, int index) {
        return const PaddingDivider();
      },
    );
  }
}
